import logging

from pylons import request
import pylons.decorators

from cibynet.lib.base import BaseController, render
from cibynet.lib.utils import ajax_validator
from cibynet.model import utils as m_utils
from cibynet.model.m_users import username_new_validator
from cibynet.model.m_machines import hostname_new_validator
from cibynet.model.m_machines import macaddress_validator

log = logging.getLogger(__name__)

class AjaxController(BaseController):
  """Defines several methods usable by remote javascript.
  """

  @pylons.decorators.jsonify
  @ajax_validator
  def validate_username(self):
    """Validate the username to create a new user.
    If the username has already been attributed
    then returns False, otherwise returns True.
    """
    username = unicode(request.GET.get("username"))
    return username_new_validator.to_python(username)

  @pylons.decorators.jsonify
  @ajax_validator
  def validate_hostname(self):
    """Validate the hostname to create a new machine.
    If the hostname has already been attributed
    then returns False, otherwise returns True.
    """
    hostname = unicode(request.GET.get("hostname"))
    return hostname_new_validator.to_python(hostname)
  
  @pylons.decorators.jsonify
  @ajax_validator
  def validate_macaddress(self):
    """Validate a MAC address: must have 12 hexa chars.
    """
    mac = unicode(request.GET.get("macaddress"))
    return macaddress_validator.to_python(mac)